import re

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError

from utils.base import BaseModel


class User(AbstractUser, BaseModel):
    email = models.EmailField(help_text='邮箱', unique=True)
    role = models.ForeignKey('Role', help_text='所属角色', on_delete=models.DO_NOTHING)

    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

    REQUIRED_FIELDS = ['email']


# class UserProject(BaseModel):
#     user = models.ForeignKey(User, on_delete=models.PROTECT)
#     project = models.ForeignKey('projects.Project', on_delete=models.DO_NOTHING)
#     is_leader = models.BooleanField(default=False, help_text='是否是项目负责人')
#
#     class Meta:
#         db_table = 'tb_user_project'
#         verbose_name = '用户项目表'
#         verbose_name_plural = verbose_name


class Role(BaseModel):
    name = models.CharField('角色名称', help_text='角色名称', max_length=20, unique=True)
    permission = models.ManyToManyField('Permission', help_text='所属角色', through='RolePermission')

    def users(self):
        return self.user_set.count()

    def permissions(self):
        return RolePermission.objects.filter(role_id=self, has_permission=True).count()

    class Meta:
        db_table = 'tb_role'
        verbose_name = '角色表'
        verbose_name_plural = verbose_name


class RolePermission(BaseModel):
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
    permission = models.ForeignKey('Permission', on_delete=models.DO_NOTHING)
    has_permission = models.BooleanField('是否有权限', default=False)
    has_read_permission = models.BooleanField('是否有读的权限', default=False)
    has_edit_permission = models.BooleanField('是否有编辑权限', default=False)
    has_add_permission = models.BooleanField('是否有新增权限', default=False)
    has_delete_permission = models.BooleanField('是否有删除权限', default=False)

    class Meta:
        db_table = 'tb_role_permission'
        verbose_name = '角色权限表'
        verbose_name_plural = verbose_name


class Permission(BaseModel):
    class MenuLevel(models.IntegerChoices):
        FIRST_MENU = 1, '一级菜单'
        SECOND_MENU = 2, '二级菜单'

    name = models.CharField('菜单名称', max_length=20, help_text='权限名称')
    level = models.IntegerField(choices=MenuLevel.choices, default=MenuLevel.FIRST_MENU, help_text='菜单类型')
    parent = models.IntegerField('父ID', help_text='父ID', default=0)
    path = models.CharField('菜单跳转路径', max_length=50, help_text='菜单跳转路径')
    icon = models.CharField('菜单图标', max_length=20, help_text='菜单图标')

    class Meta:
        db_table = 'tb_permission'
        verbose_name = '权限表'
        verbose_name_plural = verbose_name

